package com.oss.service.oss;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oss.dto.oss.DeleteByIdDto;
import com.oss.dto.oss.partnershare.PartnerShareAddDto;
import com.oss.dto.oss.partnershare.PartnerSharePageDto;
import com.oss.dto.oss.partnershare.PartnerShareUpdateDto;
import com.oss.entity.oss.PartnerShare;
import com.oss.enums.IsDeletedEnum;
import com.oss.mapper.oss.PartnerShareMapper;
import com.oss.service.system.DictionaryService;
import com.oss.service.system.UserService;
import com.oss.util.SnowFlakeUtil;
import com.oss.vo.oss.partnershare.PartnerShareVO;
import com.oss.vo.oss.student.StudentVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author chengqiang
 */
@Service
public class PartnerShareService extends ServiceImpl<PartnerShareMapper, PartnerShare> {
    @Autowired
    UserService userService;
    @Autowired
    StudentService studentService;
    @Autowired
    DictionaryService dictionaryService;

    public IPage<PartnerShareVO> selectByPage(PartnerSharePageDto dto) {
        LambdaQueryWrapper<PartnerShare> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PartnerShare::getIsDeleted, IsDeletedEnum.NO.getFlag());
        wrapper.eq(StringUtils.isNotBlank(dto.getStudentID()),PartnerShare::getStudentID,dto.getStudentID());
        wrapper.eq(StringUtils.isNotBlank(dto.getProductType()),PartnerShare::getProductType,dto.getProductType());
        wrapper.eq(dto.getVipServer() != null,PartnerShare::getVipServer,dto.getVipServer());
        Map<String, StudentVO> studentMap = new HashMap<>();
        if (dto.getDateStart() != null) {
            wrapper.ge(PartnerShare::getDate,dto.getDateStart());
        }
        if (dto.getDateEnd() != null) {
            wrapper.le(PartnerShare::getDate,dto.getDateEnd());
        }
        IPage<PartnerShare> page = this.page(new Page<>(dto.getPageNo(), dto.getPageSize()), wrapper);
        if (CollectionUtils.isNotEmpty(page.getRecords())){
            Set<String> ids = page.getRecords().stream().map(PartnerShare::getStudentID).collect(Collectors.toSet());
            studentMap = studentService.selectByIDs(ids);
        }
        Map<String,String> purchaseCoursesmap = dictionaryService.getDictionaryMapByTypeCode("PartnershipInterest");
        Map<String, StudentVO> finalStudentMap = studentMap;
        // 重心币余额 = 购买份数 *   所有记录中字段权益类型对应字典的value的最大值(数据库中存的就是值 , 直接取最大值即可)
        LambdaQueryWrapper<PartnerShare> maxWrapper = new LambdaQueryWrapper<>();
        maxWrapper.eq(PartnerShare::getIsDeleted, IsDeletedEnum.NO.getFlag());
        maxWrapper.orderByDesc(PartnerShare::getProductType);
        maxWrapper.last("limit 1");
        PartnerShare maxPartnerShare =this.getOne(maxWrapper);
        // 取最大的权益类型值
        String finalDicValue = maxPartnerShare == null ? "0": maxPartnerShare.getProductType();

        return page.convert(entity->{
            PartnerShareVO vo = new PartnerShareVO();
            BeanUtils.copyProperties(entity,vo);
            vo.setProductType(purchaseCoursesmap.get(entity.getProductType()));
            if (finalStudentMap.containsKey(entity.getStudentID())){
                StudentVO studentVO = finalStudentMap.get(entity.getStudentID());
                vo.setStudentID(studentVO.getId());
                vo.setStudentPhone(studentVO.getPhone());
                vo.setStudentName(studentVO.getName());
                vo.setStudentWechatID(studentVO.getWechatID());
                vo.setStudentAccount(studentVO.getAccount());
                vo.setCode(studentVO.getCode());
                if (entity.getProductType() != null){
                    // 重心币价值=记录中最大值*购买份数/权益类型对应的字典值
                    BigDecimal value = new BigDecimal(finalDicValue).multiply(entity.getBuyCopies());
                    BigDecimal newValue = new BigDecimal(entity.getProductType());
                    vo.setValue(value.divide(newValue, BigDecimal.ROUND_HALF_UP));
                }
            }
            return vo;
        });
    }

    public String add(PartnerShareAddDto dto) {
        PartnerShare entity = new PartnerShare();
        BeanUtils.copyProperties(dto,entity);
        entity.setId(SnowFlakeUtil.getID());
        this.save(entity);
        return "操作成功";
    }

    public String updateData(PartnerShareUpdateDto dto) {
        PartnerShare entity = new PartnerShare();
        BeanUtils.copyProperties(dto,entity);
        this.updateById(entity);
        return "操作成功";
    }

    public String delete(DeleteByIdDto dto) {
        LambdaUpdateWrapper<PartnerShare> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(PartnerShare::getId,dto.getId());
        lambdaUpdateWrapper.set(PartnerShare::getIsDeleted,IsDeletedEnum.YES.getFlag());
        this.update(null,lambdaUpdateWrapper);
        return "操作成功";
    }

}
